package com.hang.ad.index.creativeUnit;

import com.hang.ad.index.IndexAware;
import com.hang.ad.index.adunit.AdUnitObject;
import com.hang.ad.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;

@Slf4j
@Component
public class CreativeUnitIndex implements IndexAware<String, CreativeUnitObject> {
    //<adId-unitId, creativeUnitObject>
    private static Map<String, CreativeUnitObject> creativeMap;
    //<adId, unitId set>
    private static Map<Long, Set<Long>> adIdMap;
    //<unitId, adId set>
    private static Map<Long, Set<Long>> unitIdMap;
    static {
        creativeMap = new ConcurrentHashMap<>();
        adIdMap = new ConcurrentHashMap<>();
        unitIdMap = new ConcurrentHashMap<>();
    }

    @Override
    public CreativeUnitObject get(String key) {

        return creativeMap.get(key);
    }

    @Override
    public void update(String key, CreativeUnitObject value) {
        log.error("不支持update");
    }

    @Override
    public void add(String key, CreativeUnitObject value) {
        creativeMap.put(key, value);
        Set<Long> unitIdSet = adIdMap.get(value.getAdId());
        if (CollectionUtils.isEmpty(unitIdSet)){
            adIdMap.put(value.getAdId(), new ConcurrentSkipListSet<>());
        }
        unitIdSet.add(value.getUnitId());

        Set<Long> adIdSet = unitIdMap.get(value.getUnitId());
        if (CollectionUtils.isEmpty(adIdSet)){
            unitIdMap.put(value.getUnitId(), new ConcurrentSkipListSet<>());
        }
        adIdSet.add(value.getAdId());
    }

    @Override
    public void delete(String key, CreativeUnitObject value) {
        creativeMap.remove(key);
        Set<Long> unitIdSet = adIdMap.get(value.getAdId());
        if (CollectionUtils.isNotEmpty(unitIdSet)){
            unitIdSet.remove(value.getUnitId());
        }
        Set<Long> adIdSet = unitIdMap.get(value.getUnitId());
        if (CollectionUtils.isNotEmpty(adIdSet)){
            adIdSet.remove(value.getAdId());
        }
    }

    public List<Long> selectAds(List<AdUnitObject> objects){
        if (CollectionUtils.isEmpty(objects)){
            return Collections.emptyList();
        }
        List<Long> result = new ArrayList<>();

        for (AdUnitObject object : objects) {
            Set<Long> adIds = unitIdMap.get(object.getUnitId());
            if (CollectionUtils.isNotEmpty(adIds)){
                result.addAll(adIds);
            }
        }
        return result;
    }
}
